<template>
  <div class="tree-wrapper">
    <a-tree
      blockNode
      v-model:selectedKeys="selectedKeys"
      v-model:expanded-keys="expandedKeys"
      :auto-expand-parent="autoExpandParent"
      :defaultSelectedKeys="selectedKeys"
      :loadedKeys="loadedKeys"
      :replace-fields="replaceFields"
      :tree-data="treeData"
      @select="onSelect"
    >
      <template v-slot:name="node">
        {{ node.name }}
        <operate-row
          :hide-del="getPosLength(node) < 3 || !hasPermission('dept:delete')"
          :hide-add="!hasPermission('dept:add')"
          :hide-edit="!hasPermission('dept:update')"
          @delete="deleteRow(node)"
          @add="addRow(node)"
          @edit="editRow(node)"
        />
      </template>
    </a-tree>
  </div>
</template>

<script lang="ts">
import { message, Tree } from 'ant-design-vue'
import { defineComponent, toRefs, SetupContext, reactive, onMounted, nextTick, unref } from 'vue'
import { OperateRow } from '@/components/operate-row'
import { generateTree } from '@/utils/common'
import { deptAll, deptDelete, deptSelectbyName } from '@/api/dept'
import AddModal from '@/views/terminal/treeComponents/add-modal.vue'
import EditModal from '@/views/terminal/treeComponents/edit-modal.vue'
import { useEventbus } from '@/hooks/useEventbus'
import { useCreateModal } from '@/hooks'
import { hasPermission } from '@/utils/hasPermission'

interface TreeItem {
  title: string | number;
  key: string | number;
  children?: TreeItem[];
  scopedSlots?: object;

  [propName: string]: any;
}

export default defineComponent({
  name: 'dept-tree',
  emits: ['update:departmentid'],
  props: {
    departmentid: {
      type: [String, Number]
    },
    rootTreeOption: {
      // 根树配置
      type: Object,
      default: () => ({
        title: '公司',
        key: '1'
      })
    }
  },
  components: { OperateRow, [Tree.name]: Tree },
  setup(props, context: SetupContext) {
    //事件主线
    const { refreshTree } = useEventbus()

    const state = reactive({
      replaceFields: {
        title: 'name',
        key: 'departmentid'
      },
      expandedKeys: [props.rootTreeOption.key],
      autoExpandParent: true,
      loadedKeys: [],
      checkedKeys: [],
      selectedKeys: [props.rootTreeOption.key],
      treeData: [] as any
    })

    // 获取部门树
    const getDeptTree = async (fatherId: string | number) => {
      const param = {
        ID: fatherId
      }
      const { data } = await deptAll(param)
      console.log(data, 'data')
      return generateTree(data, 1)
    }

    // 初始化树
    const initDeptTree = async () => {
      const data = await deptSelectbyName({ name: 'root' })
      const children = await getDeptTree(data.departmentid)
      state.treeData = [
        {
          ...data,
          slots: { title: 'name' },
          children
        }
      ]
      console.log(state.treeData)
      state.expandedKeys = [data.departmentid]
      state.selectedKeys = [data.departmentid]
      context.emit('update:departmentid', data.departmentid)
    }

    onMounted(() => {
      refreshTree(() => {
        initDeptTree()
      })
      initDeptTree()
    })

    const onLoadData = treeNode => {
      return new Promise((resolve: (value?: unknown) => void) => {
        if (treeNode.dataRef.children) {
          treeNode.dataRef.isLeaf = true
          console.log(treeNode.dataRef.children, '木有了')
          resolve()
          return
        }
        (async () => {
          // treeNode.vcTreeNode.dataRef.isLeaf = false
          treeNode.dataRef.isLeaf = true
          // treeNode.dataRef.children = await getDeptTree(treeNode.eventKey).finally(() => resolve())
          nextTick(() => (treeNode.dataRef.isLeaf = false))
          return resolve()
        })()
        // state.treeData = [...state.treeData];
      })
    }

    const onSelect = (selectedKeys: any, info: any) => {
      const { node } = info
      context.emit('update:departmentid', node.eventKey.toString())
      state.selectedKeys = [node.eventKey]
    }
    // 获取节点层级
    const getPosLength = (node): number => node.pos.split('-').length

    // 删除行
    const deleteRow = async node => {
      const { eventKey, parent, children } = node
      const params = {
        departmentid: eventKey,
        parentid: parent,
        isParent: children.length != 0
      }
      const res = await deptDelete(params)
      if (res.code == 0) {
        message.success('删除成功')
        initDeptTree()
      } else {
        message[res.type](res.message || '删除失败')
      }
    }
    // 添加行
    const addRow = node => {
      useCreateModal(AddModal, {
        departmentid: node.eventKey,
        callback: () => initDeptTree()
      })
    }
    // 编辑行
    const editRow = node => {
      node.dataRef.ipSetting = node.dataRef.ipsetting
      useCreateModal(EditModal, {
        departmentid: node.eventKey,
        fields: node.dataRef,
        callback: () => initDeptTree()
      })
    }

    return {
      ...toRefs(state),
      getPosLength,
      onSelect,
      onLoadData,
      deleteRow,
      addRow,
      editRow,
      hasPermission
    }
  }
})
</script>

<style lang="scss" scoped>
.tree-wrapper {
  overflow: auto;

  ::v-deep(.ant-tree-title) {
    display: inline-block;
    width: 100%;

    &:hover .actions {
      display: inline-block;
    }
  }
}
</style>
